#!/bin/bash
#Андрей Халиуллин
foo () 
{
	name="$@"
	base=$(basename "$name")
	echo "$base"
	if [[ -d "$name" ]]
	then
		echo "mkdir \"$base\" &>/dev/null"
		echo "cd \"$base\""
		cd "$name"
		shopt -s nullglob
		for a in *
		do
			if [[ "$scriptdir" != "$(pwd)" ]] || [[ "$a" != "$script" ]]
			then
				foo "$a"
			fi
		done
		cd ../
		echo "cd ../"
	else
		echo -e "if [[ -e \"$base\" ]]\nthen\necho \"File \$(pwd)/$base already exist, doing nothing\"\nelse"
		echo -e "cat << 'EOF'|head -c -1 > \"$base\""
		cat "$name"|sed -e "
		s/^EOF/EOF\necho -ne \"\nEOF\" >> \"$base\"\ncat << 'EOF'|head -c -1 >> \"$base\"\n/
		s/\o00\o00*/\nEOF\necho -ne \"&\" >> \"$base\"\ncat << 'EOF'|head -c -1 >> \"$base\"\n/g
		s/\o00/\\\\x00/g
		"
		echo -e "\nEOF\necho \"\$(pwd)/$base\"\nfi"
	fi
}
if [[ -z $1 ]] || [[ -z $2 ]]
then 
	echo "I need 2 or more params." >&2
	exit 1
fi
original="$1"
script="$1"
scriptdir=$(pwd)
while [[ -e "$script" ]]
do
	script="$script tmp"
done
echo "#!/bin/bash" > "$script"
shift
until [[ -z $1 ]]
do
	foo "$1" >>"$script"
	shift
done
echo -e "\necho \"Done.\"" >> "$script"
if [[ "$original" != "$script" ]]
then
	mv "$script" "$original"
fi
